<template>
  <div ref="bar" :class="className" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import * as echarts from 'echarts/core'
import { GridComponent } from 'echarts/components'
import { BarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { debounce } from 'lodash'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import 'echarts/theme/macarons'

echarts.use([GridComponent, BarChart, CanvasRenderer])

const animationDuration = 2000

defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  }
})

let chart = null
const bar = ref(null)

function initChart() {
  chart = echarts.init(bar.value, 'macarons')

  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      top: 10,
      left: '2%',
      right: '2%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisTick: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '单选题',
        type: 'bar',
        stack: 'vistors',
        barWidth: '60%',
        data: [79, 52, 200, 334, 390, 330, 220],
        animationDuration
      },
      {
        name: '多选题',
        type: 'bar',
        stack: 'vistors',
        barWidth: '60%',
        data: [80, 52, 200, 334, 390, 330, 220],
        animationDuration
      },
      {
        name: '简答题',
        type: 'bar',
        stack: 'vistors',
        barWidth: '60%',
        data: [30, 52, 200, 334, 390, 330, 220],
        animationDuration
      }
    ]
  })
}

const __resizeHandler = debounce(() => {
  if (chart) {
    chart.resize()
  }
}, 100)
onMounted(() => {
  initChart()

  window.addEventListener('resize', __resizeHandler)
})

onBeforeUnmount(() => {
  if (!chart) {
    return
  }
  window.removeEventListener('resize', __resizeHandler)
  chart.dispose()
  chart = null
})
</script>
